package com.yancloud.android.contractclient.nativesclient;

import android.util.Log;

import com.google.gson.Gson;
import com.yancloud.android.contractclient.ResultCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.CloseReason;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;

import crypto.SM2;

public class BaseClient extends Endpoint {
	private Session session;
	private boolean isConnected;
	private WSHandler handler;

	public BaseClient() {
		isConnected = false;
		handler = new WSHandler(this);
	}

	@Override
	public void onOpen(Session session, EndpointConfig config) {
		this.session = session;
		session.addMessageHandler(handler);
		Map<String, String> setNodeID = new HashMap<String, String>();
		setNodeID.put("action", "setNodeID");
		setNodeID.put("id", handler.keyPair.getPublicKeyStr());
		SM2.Signature sig = new SM2().sign(handler.keyPair.getPublicKeyStr().getBytes(),
				handler.keyPair.getPrivateKey().toString(16));
		setNodeID.put("signature", sig.toString());
		setNodeID.put("nodeName","ContractManager@Phone");
		try {
			session.getBasicRemote().sendText(new Gson().toJson(setNodeID));
		} catch (IOException e) {
			e.printStackTrace();
		}

		isConnected = true;
	}

	@Override
	public void onClose(Session session, CloseReason config) {
		this.session = null;
		isConnected = false;
	}

	@Override
	public void onError(Session session, Throwable config) {
		this.session = null;
		isConnected = false;
	}

	public synchronized  void sendText(final String text) {

			Runnable run = new Runnable() {
				@Override
				public void run() {
					try {
					    Gson gson = new Gson();
						if (text.length() > 64536) {
							Map<String, String> seg = new HashMap<>();
							seg.put("isSegment", "true");
							for (int i = 0; i < text.length(); i += 32536) {
								int off = i + 32536;
								if (off > text.length())
									off = text.length();
								if (off == text.length())
									seg.put("isSegment", "false");
								seg.put("data", text.substring(i, off));
								String toSend = gson.toJson(seg);
								Log.d("BaseClient","send Len:"+toSend.length());
								BaseClient.this.session.getBasicRemote().sendText(toSend);
							}
						} else {
							BaseClient.this.session.getBasicRemote().sendText(text);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			};

			run.run();


	}

	public boolean connected() {
		return this.session!=null && this.session.isOpen();
	}

	public void updateContract() {
		handler.controller.updateContract(new ResultCallback() {
			@Override
			public void onResult(String str) {
				System.out.println(str);
			}
		});
	}
}
